/**
 * Created by Weizehua on 2017/1/28.
 */
import {suite, test} from "mocha-typescript";
import {Injector, Injectable} from "ts.di";
import {Request} from "../Core/Request";
import {Hash} from "../../src/Core/Hash/Hash";
import {assertHandlerSuccess, assertHandlerFail} from "../Core/Utils";
import {generateUploadInfoFromUrl, generateUploadInfoFromPath} from "../Core/UploadInfoGenerator";
import {Connection} from "typeorm";
import {User} from "../../src/User/User";
import {equal} from "assert";
import {Album} from "../../src/Album/Album";
import {generateSign} from "../Core/SignatureGenerator";

@Injectable()
@suite
export class NewImageRequestTest {
    static user:User;
    static album:Album;
    static async before(){
        // insert user
        let typeorm = Injector.get(Connection);
        let u = new User();
        u.username = "test" + Math.random();
        NewImageRequestTest.user = await typeorm.entityManager.persist(u);
        equal(!!NewImageRequestTest.user, true);

        // insert album
        let a = new Album();
        a.imageSource = "";
        a.title = "";
        NewImageRequestTest.album = await typeorm.entityManager.persist(a);
        equal(!!NewImageRequestTest.album, true);
    }

    static async after() {
        let typeorm = Injector.get(Connection);
        let userRemove = await typeorm.entityManager.remove(NewImageRequestTest.user);
    }

    @test
    async '/image/new - message - no spots: should pass'() {
        let path = "test path" + Math.random();
        let params = {
            uploadInfo: await generateUploadInfoFromPath(path),
            spots: [],
            albumId: NewImageRequestTest.album.id
        };
        let res = await Request.userGet('/image/new', await generateSign(['uploadInfo'], params));
        assertHandlerSuccess(res);
    }

    @test
    async '/image/new - message: should pass: one spot'() {
        let path = "test path" + Math.random();
        let signature = await Injector.get(Hash).sign(path);
        let params = {
            uploadInfo: await generateUploadInfoFromPath(path),
            spots: [{x: 1, y: 1, title: '12345', detail: 'detail'}],
            albumId: NewImageRequestTest.album.id
        };
        let res = await Request.userGet('/image/new', await generateSign(['uploadInfo'], params));
        assertHandlerSuccess(res);
    }

    @test
    async '/image/new - message(anti-x): should failed: when spot title too long'() {
        let path = "test path" + Math.random();
        let signature = await Injector.get(Hash).sign(path);
        let params = {
            uploadInfo: await generateUploadInfoFromPath(path),
            spots: [{x: 1, y: 1, title: '1234567', detail: 'detail'}],
            albumId: NewImageRequestTest.album.id
        };
        let res = await Request.userGet('/image/new', await generateSign(['uploadInfo'], params));
        assertHandlerFail(res);
    }
}
